package com.xuecheng.base.exception;

import com.xuecheng.base.model.ResultResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    
//    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 处理自定义异常
     *
     * @param customException 自定义异常
     * @return {@link ResultResponse}
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public ResultResponse customExceptionHandler(CustomException customException){
        log.error("发生业务异常！原因是：{}",customException.getErrorMsg());
        return ResultResponse.error(customException.getErrorCode(),customException.getErrorMsg());
    }


    /**
     * 处理空指针的异常
     *
     * @param nullPointerException 空指针异常
     * @return {@link ResultResponse}
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ResultResponse nullPointerException(NullPointerException nullPointerException){
        log.error("发生空指针异常！原因是:",nullPointerException);
        return ResultResponse.error(CustomExceptionEnum.BODY_NOT_MATCH);
    }


    /**
     * 方法参数无效
     *
     * @param e 方法参数无效
     * @return {@link ResultResponse}
     */
    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public ResultResponse methodArgumentNotValidException(BindException  e){

        BindingResult bindingResult = e.getBindingResult();
        StringBuilder stringBuffer = new StringBuilder();

        bindingResult.getFieldErrors().forEach(item->{
            if(stringBuffer.length()>0){
                stringBuffer.append(",");
            }
            stringBuffer.append(item.getDefaultMessage());
        });

        log.error("发生数据校验异常！原因是:",e);
        return ResultResponse.error(String.valueOf(stringBuffer));
    }

    /**
     * 处理其他异常
     *
     * @param exception 异常
     * @return {@link ResultResponse}
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultResponse exceptionHandler(Exception exception){
        log.error("未知异常！原因是:",exception);
        return ResultResponse.error(CustomExceptionEnum.INTERNAL_SERVER_ERROR);
    }
}

